package com.example.arithmeticleetcode.leetcode.dec;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-12-21 09:17
 **/
public class Demo18 {

    public static void main(String[] args) {
//        System.out.println(reformatNumber("1-23-45 6"));
//        System.out.println(reformatNumber("123 4-567"));
//        System.out.println(reformatNumber("123 4-5678"));
//        System.out.println(reformatNumber("12"));
//        System.out.println(reformatNumber("--17-5 229 35-39475 "));
//        String s = "123-456-";
//        System.out.println(s.substring(0, s.length() - 1));

        StringBuffer sb = new StringBuffer();
        sb.append(1);
        sb.append(2);
        sb.append(3);
        sb.deleteCharAt(sb.length() - 2);
        System.out.println(sb.toString());
        sb.insert(sb.length() - 2, '-');
        System.out.println(sb.toString());
    }

    public static String reformatNumber(String number) {
        StringBuffer sb = new StringBuffer();
        int count = 0;
        for (int i = 0, len = number.length(); i < len; i++) {
            char c = number.charAt(i);
            if (c == '-' || c == ' ') continue;
            sb.append(c);
            if (++count % 3 == 0) sb.append("-");
        }
        String s = sb.toString();
        int mod = count % 3;
        if (mod == 0) {
            s = s.substring(0, s.length() - 1);
        }
        else if (mod == 1) {
            int length = s.length();
            String substring1 = s.substring(0, length - 5);
            String substring2 = s.substring(length - 5, length - 3);
            String substring3 = s.substring(length - 3, length - 2);
            String substring4 = s.substring(length - 2, length - 1);
            String substring5 = s.substring(length - 1);
            return substring1 + substring2 + substring4 + substring3 + substring5;
        }
        return s;
    }
}
